import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { _HttpClient, SettingsService, TitleService } from '@delon/theme';
import { OrderService } from '../../../service/order/order.service';
import { SimpleTableComponent, SimpleTableColumn } from '@delon/abc/src/simple-table';
import { CommService } from '../../../service/comm/comm.service';
import { ServiceResult } from '@core/constant';
import { formatDate } from '@angular/common';
import { Router } from '@angular/router';
import { EmitterService } from 'app/service/emit.service';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { UserSelectModalComponent } from '@shared/component/users/user-select-modal.component';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Component({
  selector: 'willsend-list',
  templateUrl: './willsend-list.component.html',
  styleUrls: ['./willsend-list.component.less']
})
export class WillSendListComponent implements OnInit, OnDestroy {  
  ps = 30;
  q: any = {  
    mode: 'other',    
    orderId: '',
    willsend: '1',
    dateRange: null,
    pending: '1'
  };  
  url = this.orderServ.list();
  data = [];
  loading = false;
  statuss = [
    { text: 'Pending', value: '1'},  // 未完成   
    { text: 'Complete', value: '0'} // 完成
  ];
  @ViewChild('st') st: SimpleTableComponent;
  @ViewChild('st1') st1: SimpleTableComponent;
  barcode;
  dateFormat = 'yyyy/MM/dd';
  columns: SimpleTableColumn[] = [];
  subColumns: SimpleTableColumn[] = [
    { title: 'SKU', index: 'productCd', width: '25%' },
    { title: '发货数量', index: 'qty', i18n: 'qty', type: "number", width: '25%' },
    { title: '已发数量', index: 'sendQty', i18n: 'sendQty', type: "number", width: '25%'  },
    { title: '未发数量', i18n: 'wf', render: 'wf', type: "number", width: '25%' }     
  ];
  visible = false;
  currentRow: { [propName: string]: any } = {}

  constructor(
      private orderServ: OrderService,
      private emit: EmitterService,
      private titleService: TitleService,
      private router: Router,
      private setting: SettingsService,
      private modalService: NzModalService,
      private msg: NzMessageService
  ) {}
  

  ngOnInit() {
    this.buildColumn();
    // 隐藏reusetab
    setTimeout(() => {
        this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 100);    
    this.titleService.setTitle("按单发货");    
  }

  back() {
      this.router.navigate(['/workplace/list']);
  }

  // 显示reusetab
  ngOnDestroy() {    
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  buildColumn() {
    this.columns = [        
        { title: '单号', index: 'orderId', i18n: 'orderId', type: "link",
          click: (record: any, instance?: SimpleTableComponent) => {
              this.currentRow.id = record.id;
              this.open();
          }
        },
        { title: '提交日期', index: 'createDate', i18n: 'createDate' },       
        { title: '客户', index: 'clientName', i18n: 'user' },
        { title: '发货数量', index: 'qty', i18n: 'qty', type: "number" },
        { title: '已发数量', index: 'sendQty', i18n: 'sendQty', type: "number"  },
        { title: '未发数量', i18n: 'wf', render: 'wf', type: "number" }      
    ];
  }

  dateChange(result: Date[]): void {
    if (result.length != 0) {
      this.q.startDate = formatDate(result[0], 'yyyy-MM-dd', 'en-US');
      this.q.endDate = formatDate(result[1], 'yyyy-MM-dd', 'en-US');
    } else {
      this.q.startDate = '';
      this.q.endDate = '';
    }
  }
  
  showUserSelect() {
    let level = 'FIRST';
    if (this.setting.user.isManager) {
      level = 'FIRST';
    } else if (this.setting.user.level === 'FIRST') {
      level = 'SECOND';
    } else if (this.setting.user.level === 'SECOND') {
      level = 'THIRD';
    }
    const modal = this.modalService.create({
        nzContent: UserSelectModalComponent, 
        nzWidth: '730px', 
        nzComponentParams: { selectLevel: level, lockLevel: true, multi: false },                  
        nzFooter: null
    }); 
    modal.afterOpen.subscribe(() => {
        modal.getContentComponent().getSubject().subscribe(data => {
            let users = data as Array<any>; 
            if (users && users.length != 0) {
              this.q.username = users[0].username;
            }                                                         
        })
    })
  }  

  open(): void {
    if (this.currentRow.id) {
        this.orderServ.detail(this.currentRow.id, true).pipe(catchError(err => {
            return of(err)
        })).subscribe(data => {
            if (data.status === 200) {
                this.currentRow = data.data;
                this.visible = true;
            } else {
                this.msg.error(data.message);
            }
        })
    }   
  }

  close(): void {
    this.visible = false;
    this.st.reload();
  }

  send(event) {
      if (event.keyCode === 13) {    
          this.loading = true;      
          this.orderServ.send2Client(this.currentRow.orderId.substring(1), this.barcode).pipe(catchError(err => {
              return of(err)
          })).subscribe(data => {
              this.loading = false;
              if (data.status === 200) {
                this.barcode = "";
                this.msg.success('Scan successful');
                // 成功重新加载
                this.orderServ.detail(this.currentRow.orderId.substring(1), true).pipe(catchError(err => {
                    return of(err)
                })).subscribe(data => {
                    if (data.status === 200) {
                        this.currentRow = data.data;  
                        this.st1.reload();                     
                    } 
                })
              } else {
                this.error('Scan failed', data.message);
              }
          })
      }
  }

  error(title, message): void {
    this.modalService.error({
      nzTitle: title,
      nzContent: message
    });
  }
}